# 创建时间:2023/4/16 12:09
# 创建人:天霄
# 计划 :SenjoTwintail
# 文件 :add_record_content.py
# 基于 Python 3.8.2
# ========================================
# 操作数据库pyqt工具
# ========================================
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from Api.DataApi import _BaseApi


baseApi = _BaseApi()


class ToDataBase(QTabWidget):
    def __init__(self, parent=None):
        roles = baseApi.GetSoldierByAnyCode(None)
        baseApi.close_cursor()
        self.role_rec_id = None
        '''当前角色记录id，可能有多个'''
        self.roles = [(r[1].role_id, r[1].name) for r in roles]  # 角色ID、名称
        super(ToDataBase, self).__init__(parent)
        self.setFont(QFont('微软雅黑', 10))

        self.tab1 = QWidget(self)
        self.tab1_nowRoleRecordID = 0
        self.tab2 = QWidget(self)
        self.tab3 = QWidget(self)
        self.tab99 = QWidget(self)

        self.addTab(self.tab1, '添加角色故事')
        self.addTab(self.tab2, 'Tab 2')
        self.addTab(self.tab3, 'Tab 3')
        self.addTab(self.tab99, '关于')

        self.tab1_添加角色故事()
        self.tab99_about_ui()

        self.resize(720, 420)  # 初始窗口大小
        self.setWindowTitle("战场双马尾-数据库工具")

    def closeEvent(self, event):
        """改写：关闭事件触发后弹出确认框"""
        reply = QMessageBox.question(self, '提示', '确认关闭窗口？', QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    def tab1_添加角色故事(self):
        """添加角色故事"""
        # 第一行
        lbl_role = QLabel("角色：")
        lbl_role.setAlignment(Qt.AlignRight | Qt.AlignCenter)
        self.tab1_roles_cbb = QComboBox(self)
        self.tab1_roles_cbb.addItem('请选择角色', 0)
        for role_id, role_name in self.roles:
            self.tab1_roles_cbb.addItem(role_name, role_id)
        self.tab1_roles_cbb.currentIndexChanged.connect(self.tab1_refresh_changed)

        lbl_rectype = QLabel("记录类型：")
        lbl_rectype.setAlignment(Qt.AlignRight | Qt.AlignCenter)
        self.tab1_rectype_cbb = QComboBox(self)
        self.tab1_rectype_cbb.addItem('请选择记录类型', 0)
        self.tab1_rectype_cbb.addItem('犯罪记录', 1)
        self.tab1_rectype_cbb.addItem('角色故事', 2)
        self.tab1_rectype_cbb.addItem('私密记事', 3)
        self.tab1_rectype_cbb.currentIndexChanged.connect(self.tab1_refresh_changed)

        # 第二行
        lbl_title = QLabel("标题：")
        lbl_title.setAlignment(Qt.AlignRight | Qt.AlignCenter)
        self.tab1_le_title = QLineEdit(self)
        self.tab1_le_title.setPlaceholderText('标题')

        # 第三行
        lbl_content = QLabel("内容：")
        lbl_content.setAlignment(Qt.AlignRight | Qt.AlignCenter)
        # 第四行
        self.tab1_te_content = QTextEdit()
        # 第五行
        self.tab1_btn_save = QPushButton('保存')
        self.tab1_btn_save.clicked.connect(self.saveRoleRecordGo)

        grid = QGridLayout()
        grid.setSpacing(5)  # （行、字段）间距，即网格线宽度

        grid.addWidget(lbl_role, 1, 1)
        grid.addWidget(self.tab1_roles_cbb, 1, 2, 1, 2)
        grid.addWidget(lbl_rectype, 1, 4)
        grid.addWidget(self.tab1_rectype_cbb, 1, 5, 1, 2)

        grid.addWidget(lbl_title, 2, 1)
        grid.addWidget(self.tab1_le_title, 2, 2, 1, 5)

        grid.addWidget(lbl_content, 3, 1)
        grid.addWidget(self.tab1_te_content, 4, 1, 5, 6)
        grid.addWidget(self.tab1_btn_save, 9, 2, 1, 2)
        self.tab1.setLayout(grid)

    def tab1_refresh_changed(self):
        """更改下拉"""
        self.tab1_le_title.clear()
        self.tab1_te_content.clear()
        role_id = self.tab1_roles_cbb.currentData()
        rectype = self.tab1_rectype_cbb.currentData()
        if role_id != 0 and rectype in (1, 2):
            content_data = baseApi.GetRoleRecordContent(role_id, rectype)
            baseApi.close_cursor()
            # print(f'当前内容：{content_data}')
            if content_data:
                self.role_rec_id = content_data[0][0].role_rec_id
                self.tab1_le_title.setText(content_data[0][0].title)
                self.tab1_te_content.setText(content_data[0][1].content)
            else:
                self.role_rec_id = None

    def saveRoleRecordGo(self):
        """保存角色记录"""
        role_id = self.tab1_roles_cbb.currentData()
        if role_id == 0:
            QMessageBox.information(self, '提示', '请先选择角色！')
            return
        rectype = self.tab1_rectype_cbb.currentData()
        if rectype == 0:
            QMessageBox.information(self, '提示', '请先选择记录类型！')
            return
        title = self.tab1_le_title.text()
        content = self.tab1_te_content.toPlainText()
        if not content:
            QMessageBox.information(self, '提示', '请输入内容！')
            return
        reply = QMessageBox.question(self, '确认', '确认保存内容？', QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.No:
            return
        # print(role_id)
        # print(rectype)
        # print(title)
        # print(content)
        self.tab1_btn_save.setEnabled(False)
        self.tab1_btn_save.disconnect()
        QApplication.processEvents()
        try:
            if isinstance(self.role_rec_id, int):  # 修改
                result = baseApi.UpdateRoleRecordContent(self.role_rec_id, content, title)
            else:  # 新增
                result = baseApi.AddRoleRecordContent(role_id, content, rectype, rectype, title)
        except Exception as e:
            QMessageBox.warning(self, '失败', '保存失败！')
            # print(f'错误：{e}')
        else:
            # print(result)
            if result.get('code') != 1:
                QMessageBox.warning(self, '失败', '保存失败！')
                return
            QMessageBox.information(self, '成功', '保存成功！')
            self.tab1_refresh_changed()
        finally:
            print('_'*20)
            self.tab1_btn_save.setEnabled(True)
            self.tab1_btn_save.clicked.connect(self.saveRoleRecordGo)
            baseApi.close_cursor()

    def tab99_about_ui(self):
        """关于本应用"""
        # 第一行：作者
        lbl_author = QLabel('作者：', self)
        lbl_author.setAlignment(Qt.AlignRight | Qt.AlignCenter)
        lbl_author_detail = QLabel(self)
        lbl_author_detail.setText("天霄")

        # 第二行：基于
        lbl_with = QLabel('基于：', self)
        lbl_with.setAlignment(Qt.AlignRight | Qt.AlignCenter)
        lbl_with_detail = QLabel(self)
        lbl_with_detail.setText("Python 3.8 | PyQt5")

        # 第三行：应用版本
        lbl_version = QLabel('应用版本：', self)
        lbl_version.setAlignment(Qt.AlignRight | Qt.AlignCenter)
        lbl_version_detail = QLabel(self)
        lbl_version_detail.setText("1.0.0")

        lbl0 = QLabel(self)  # 占位
        grid = QGridLayout()
        grid.setSpacing(10)

        grid.addWidget(lbl_author, 1, 1)
        grid.addWidget(lbl_author_detail, 1, 2)

        grid.addWidget(lbl_with, 2, 1)
        grid.addWidget(lbl_with_detail, 2, 2)

        grid.addWidget(lbl_version, 3, 1)
        grid.addWidget(lbl_version_detail, 3, 2)

        grid.addWidget(lbl0, 4, 1, 5, 1)
        self.tab99.setLayout(grid)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    go = ToDataBase()
    go.show()
    sys.exit(app.exec_())
    # 菲比
